package com.leantech.android.browser.ui.search

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cscj.android.repository.db.entity.SearchEngineEntity
import com.cscj.android.repository.db.entity.SearchHistoryEntity
import com.cscj.android.repository.repo.search.SearchRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

class SearchViewModel : ViewModel(), KoinComponent {

    private val searchRepository by inject<SearchRepository>()

    fun getSearchEngines(): List<SearchEngineEntity> {
        return runBlocking {
            searchRepository.searchEngines().first()
        }
    }

    val searchHistoryFlow = searchRepository
        .searchList()
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = emptyList()
        )

    val searchRecommendFlow = searchRepository.searchRecommendList()
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = emptyList()
        )

    val searchRecommendNewFlow = searchRepository.searchRecommendNewList()
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = emptyList()
        )


    val currentSearchEngineFlow = searchRepository.currentSearchEngine()

    fun saveSearchHistory(keyword: String) {
        viewModelScope.launch {
            searchRepository.saveSearchHistory(keyword)
        }
    }


    fun deleteAllSearchHistory() {
        viewModelScope.launch {
            searchRepository.deleteAllSearchHistory()
        }
    }

    fun deleteSearchHistory(searchHistoryEntity: SearchHistoryEntity) {
        viewModelScope.launch {
            searchRepository.deleteSearchHistory(searchHistoryEntity)
        }
    }


    fun switchEngine(id: Int) {
        viewModelScope.launch {
            searchRepository.switchEngine(id)
        }
    }
}